/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { log } from 'cc';
import { conflict } from './base';
import { Macro } from './macro';

const TAG = 'lcc/core/variable.ts';

/**
 * @zh
 * 变量类
 *
 * 用于框架整体的环境变量配置，不要用于具体业务逻辑
 */
class Variable {
    /**
     * @zh
     * 单例对象
     */
    private static _instance: Variable = null!;

    /**
     * @zh
     * 获得单例对象
     */
    static get instance() {
        if (Variable._instance === null) {
            Variable._instance = new Variable();
        }
        return Variable._instance;
    }

    /**
     * 构造函数
     */
    private constructor() {}

    /**
     * @zh
     * 变量映射表
     */
    private _variableMap: { [key: string]: any } = Object.create(null);

    /**
     * @zh
     * 获得变量
     *
     * @param vname - 变量名称
     */
    get<T = any>(vname: string) {
        return this._variableMap[vname] as T;
    }

    /**
     * @zh
     * 设置变量
     *
     * @param vname - 变量名称
     * @param value - 变量值
     */
    set(vname: string, value: any) {
        if (this._variableMap[vname]) {
            conflict(TAG, `key ${vname} conflict`);
        }
        Macro.DEBUG_CORE && log(TAG, `set ${vname} => ${value}`);
        this._variableMap[vname] = value;
    }

    /**
     * @zh
     * 移除变量
     *
     * @param vname - 变量名称
     */
    remove(vname: string) {
        Macro.DEBUG_CORE && log(TAG, `remove ${vname}`);
        delete this._variableMap[vname];
    }

    /**
     * @zh
     * 格式化字符串
     *
     * @param str - 字符串
     * @param extraMap - 额外变量映射表，优先解析
     */
    formatString(str: string, extraMap: { [key: string]: any } = {}) {
        return str.replace(/\$\{([\w\d_:\.]+)\}/g, (k, m: string) => {
            let [name, params] = m.split(':');
            let value = extraMap[name] || this._variableMap[name];
            if (value) {
                if (typeof value === 'function') {
                    if (params) {
                        return value(...params.split(','));
                    } else {
                        return value();
                    }
                }
                return value;
            }
            return '${' + m + '}';
        });
    }

    /**
     * @zh
     * 格式化JSON对象
     *
     * @param json json对象
     * @param extraMap - 额外变量映射表，优先解析
     */
    formatJSON(json: any, extraMap: { [key: string]: any } = null) {
        return JSON.parse(this.formatString(JSON.stringify(json), extraMap));
    }
}

/**
 * @zh
 * 变量对象
 */
export const variable = Variable.instance;
